package com.zizy.healthexpert.Activity;


import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.zizy.healthexpert.Adapter.listAddedDishesAdapter;
import com.zizy.healthexpert.Adapter.listResultAdapter;
import com.zizy.healthexpert.Config.Config;
import com.zizy.healthexpert.Database.MyDatabase_DishesRecords;
import com.zizy.healthexpert.Practical.Practical;
import com.zizy.healthexpert.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class RecordFoodsActivity extends ActionBarActivity {
    //public static RecordFoodsActivity instance=null; // this is a instance of current activity ,you can use the member variables(exp:viewItems) in this static way

    private int dishesTime=Config.BREAKFAST;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        //this.instance=this;


        setContentView(R.layout.activity_record_foods);


        /*get dishes Time*/
        SimpleDateFormat sdFormat = new SimpleDateFormat("HH");
        Date date = new Date();
        dishesTime = Integer.parseInt(sdFormat.format(date));

        /*get view*/
        ListView listView=(ListView)findViewById(R.id.listAddedFoods);
        TextView txtDishesTime=(TextView)findViewById(R.id.txtDishesTime);
        RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        /*setView*/
        txtDishesTime.setText( Practical.getDishesTimeChinese(dishesTime));
        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                TextView txtCopies = (TextView) findViewById(R.id.txtCopies);
                txtCopies.setText((int)rating+"人");
            }
        });
        /*get item list if it is not empty*/ //TODO

//        if (viewItems.size()>0){
//            Iterator iterator=viewItems.iterator();
//            while(iterator.hasNext()){
//                listAddedDishesAdapter.addedDishes item=(listAddedDishesAdapter.addedDishes)iterator.next();
//                viewItems.add(new listAddedDishesAdapter.addedDishes(item.dishesName,item.dishesId,item.formattedNutrition));
//            }
//        }

          /*Set adapter view*/
        listAddedDishesAdapter adapter=new listAddedDishesAdapter(getApplicationContext(),R.layout.list_added_foods,Config.recordFoodsActivity.viewItems);
        listView.setAdapter(adapter);
        //listView.setMinimumHeight(listView.getMeasuredHeight() * Config.recordFoodsActivity.viewItems.size());
        listView.measure(0, 0);
        listView.setLayoutParams(new LinearLayout.LayoutParams(listView.getLayoutParams().width,Config.recordFoodsActivity.viewItems.size()*listView.getMeasuredHeight()));

        Log.e("Log in recordFoodActivity_create",String.valueOf(listView.getMeasuredHeight()));
    }
    //put a food list into a formatted nutrition list
    public static  HashMap<Integer,Double> nutAllInOne(ArrayList<listAddedDishesAdapter.addedDishes> allItems){
        String names = "";
        HashMap<Integer,Double> nutMap=new HashMap<Integer, Double>();
        for (int i=0 ; i<allItems.size();i++) {
            names += allItems.get(i).dishesName+",";
            String nut = allItems.get(i).formattedNutrition; //1,0.2;2,0.3;...
            String[] arrNut = nut.split(";");
            for (String strUnit : arrNut) {//arrNut -> 1,0.2
                if (strUnit.equals("") || strUnit.split(",")[0].equals("")) continue;
                int nutID = Integer.parseInt(strUnit.split(",")[0]);
                double nutValue = Double.parseDouble(strUnit.split(",")[1]);
                if (nutMap.get(nutID) != null) {
                    nutMap.put(nutID, nutMap.get(nutID) + nutValue);
                } else {
                    nutMap.put(nutID, nutValue);
                }
            }
        }
        return nutMap;
    }

    public void onRatingBarClicked(View v) {

    }
    /*add ok button clicked*/
    public void btnAddOkClicked(View v){
        //copies
        int copies= (((int) ((RatingBar) findViewById(R.id.ratingBar)).getRating()));//TODO
        /*open database*/
        MyDatabase_DishesRecords myDatabase_dishesRecords=new MyDatabase_DishesRecords(getApplicationContext());
        /*write to database*/
        HashMap<Integer,Double> nutMap=nutAllInOne(Config.recordFoodsActivity.viewItems);
        String names = "";
        for (int i=0 ; i<Config.recordFoodsActivity.viewItems.size();i++) {
            names += Config.recordFoodsActivity.viewItems.get(i).dishesName+",";
        }
        String nutStringNew="";
        Set set=nutMap.entrySet();

        for (Iterator iterator=set.iterator();iterator.hasNext();){
            Map.Entry<Integer,Double> entry =(Map.Entry<Integer,Double>)iterator.next();
            nutStringNew+=entry.getKey()+","+entry.getValue()/copies+";";
        }
        myDatabase_dishesRecords.insertDatabase(nutStringNew,dishesTime,names);
        Toast.makeText(getApplicationContext(),"記錄增加成功！",Toast.LENGTH_LONG).show();
        /*close database*/
        myDatabase_dishesRecords.close();
        /*clear*/
        Config.recordFoodsActivity.viewItems.clear();
        /*intent MainActivity*/
        startActivity(new Intent(RecordFoodsActivity.this, MainActivity.class));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.record_foods, menu);
        return true;
    }

    //clicked ’add new food‘  will go to search activity
    public void btnAddNewFoodClicked(View v){
        SearchActivity.mode= Config.CHOOSE;
        startActivity(new Intent(RecordFoodsActivity.this,SearchActivity.class));


    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)     {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onBackPressed() {
        startActivity(new Intent(RecordFoodsActivity.this, MainActivity.class));
        this.finish();
    }

}
